<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号" prop="tel">
        <el-input
          v-model="queryParams.tel"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡类别" prop="cardType">
        <el-select v-model="queryParams.cardType" placeholder="请选择卡类别" clearable size="small">
          <el-option
            v-for="dict in dict.type.cardType"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="cardStatus">
        <el-select v-model="queryParams.cardStatus" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.cardStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['projects:SlMemberCard:add']"
        >新增会员卡</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['projects:SlMemberCard:remove']"
        >停卡</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SlMemberCardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户昵称" align="center" prop="customName" />
      <el-table-column label="手机号" align="center" prop="tel" />
      <el-table-column label="卡类别" align="center" prop="cardType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cardType" :value="scope.row.cardType"/>
        </template>
      </el-table-column>
      <el-table-column label="次数" align="center" prop="num" />
      <el-table-column label="剩余次数" align="center" prop="leftNum" />
      <el-table-column label="开卡价格" align="center" prop="cardPrice" />
      <el-table-column label="状态" align="center" prop="cardStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cardStatus" :value="scope.row.cardStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['projects:SlMemberCard:edit']"
          >修改卡信息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-add"
            @click="handleAddCardRecord(scope.row)"
            v-hasPermi="['projects:SlMemberCard:add']"
          >规划排期</el-button>
          <el-button
            size="mini"
            type="text"
            :icon="scope.row.cardStatus === 1 ? 'el-icon-delete' : 'el-icon-check'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['projects:SlMemberCard:remove']"
          >{{scope.row.cardStatus === 1 ? '停卡' : '启用'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户会员卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="customName">
          <el-input v-model="form.customName" :placeholder="form.customId ? `${form.customName}(ID:${form.customId})` : '请选择用户'" readonly>
            <el-button slot="append" icon="el-icon-search" @click="openSelectCustomer"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="卡类别">
          <el-radio-group v-model="form.cardType">
            <el-radio
              v-for="dict in dict.type.cardType"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="次数" prop="num">
          <el-input v-model="form.num" placeholder="请输入次数" />
        </el-form-item>
        <el-form-item label="剩余次数" prop="num">
          <el-input v-model="form.leftNum" placeholder="请输入剩余次数" />
        </el-form-item>
        <el-form-item label="开卡价格" prop="cardPrice">
          <el-input v-model="form.cardPrice" placeholder="请输入开卡价格" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.cardStatus">
            <el-radio
              v-for="dict in dict.type.cardStatus"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 规划排期弹出层 -->
      <schedules-setting
        :visible.sync="SchedulesSettingVisible"
        :project-id="currentProjectForSchedules.id || 1"
        :project-num="currentProjectForSchedules.num || 1"
        :project-customer-id="currentProjectForSchedules.customId || 1"
        :project-customer-name="currentProjectForSchedules.customName || '用户'" 
        @success="handleSchedulesSuccess"
        @close="handleSchedulesClose" 
      ></schedules-setting>
    <!-- 选择会员弹框 -->
    <customer-select v-model="customerDialogVisible" @select="onCustomerSelect" />
  </div>
</template>
<script>
import { listSlMemberCard, getSlMemberCard, delSlMemberCard, addSlMemberCard, updateSlMemberCard } from "@/api/projects/SlMemberCard";
import CustomerSelect from "@/components/CustomerSelect";
import SchedulesSetting from "@/views/projects/schedules/SchedulesSetting";

export default {
  name: "SlMemberCard",
  components: {
    CustomerSelect,
    SchedulesSetting

  },
  dicts: ['cardStatus','cardType'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户会员卡表格数据
      SlMemberCardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tel: null,
        cardStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 选择弹框显示状态
      customerDialogVisible: false,
      // 规划排期弹出层
      SchedulesSettingVisible: false,
      currentProjectForSchedules: {
        id: null,
        num: 0, // 或null，根据子组件需求
        customId: null,
        customName: "", // 避免传递undefined
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户会员卡列表 */
    getList() {
      this.loading = true;
      listSlMemberCard(this.queryParams).then(response => {
        this.SlMemberCardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cardId: null,
        customId: null,
        customName: null,
        tel: null,
        num: null,
        cardPrice: null,
        cardStatus: 0,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cardId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户会员卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cardId = row.cardId || this.ids
      getSlMemberCard(cardId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户会员卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cardId != null) {
            updateSlMemberCard(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSlMemberCard(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cardIds = row.cardId || this.ids;
      this.$modal.confirm('是否确认删除用户会员卡编号为"' + cardIds + '"的数据项？').then(function() {
        return delSlMemberCard(cardIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 打开选择会员弹框 */
    openSelectCustomer() {
      this.customerDialogVisible = true;
    },

    /** 会员选择回调 */
    onCustomerSelect(customer) {
      this.form.customId = customer.id;
      this.form.customName = customer.nickname;
      this.form.tel = customer.phone;
    },

handleAddCardRecord(row) {
  // 新增：判空，避免无数据时打开弹框
  if (!row || !row.cardId) {
    this.$modal.msgWarning("请选择有效的会员卡");
    return;
  }
  // 赋值当前项目数据（传递给子组件）
  this.currentProjectForSchedules = {
    id: row.cardId, // 会员卡id
    num: row.num, // 总次数
    customName: row.customName, // 会员名称
    customId: row.customId, // 会员id
  };
  // 打开排期弹框
  this.SchedulesSettingVisible = true;
},

// 父组件中新增方法
handleSchedulesClose() {
  // 清空数据
  this.currentProjectForSchedules = {
    id: null,
    num: null,
    customId: null,
    customName: null,
  };
},

  // 新增：提成设置成功后的回调（刷新项目列表）
  handleSchedulesSuccess() {
    this.getList() // 原页面的列表刷新方法
  },

  }
};
</script>
